package com.example.demo.services;

import com.example.demo.repository.PowerRepository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class PowerService {


    private final PowerRepository powerRepository;

    public PowerService(PowerRepository powerRepository) {
        this.powerRepository = powerRepository;
    }

    /*判断用户是否拥有特定权限*/
    public boolean hasPowerByModuleID(String userID, String moduleID, String subPower) {
        String userSubPower = powerRepository.findUserIDAndModuleID(userID, moduleID);

        if (userSubPower == null || userSubPower.isEmpty()) {
            return false;
        }
        /*数据库中存储的权限以[]分开，将数据以[]作为识别分隔*/
        String pattern = "\\[" + Pattern.quote(subPower) + "\\]";
        /*精确匹配权限*/
        return Pattern.compile(pattern).matcher(userSubPower).find();
    }

    /*获取用户所有权限*/
    public List<Object> hasPowerAll(String userID) {
        List<Object[]> a = powerRepository.findAllPower(userID);
        List<Object> powers = new ArrayList<>();
        for (Object[] row : a) {
            String moduleID = (String) row[0];
            String moduleName = (String) row[1];
            String subPower = (String) row[2];
            powers.add(moduleID + "," + moduleName + "," + subPower);
        }
        return powers;
    }
    /*获取单用户单表权限*/
    public String hasPower(String userID, String moduleID) {
        return powerRepository.findOnlyPower(userID,moduleID);
    }
}
